/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sinosoft.hydra.um.utils;

import com.sinosoft.hydra.core.utils.SpringHelper;
import com.sinosoft.hydra.um.domain.model.DirectoryType;
import com.sinosoft.hydra.um.domain.permission.TDirectory;
import com.sinosoft.hydra.um.services.DirectoryService;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典工具类
 *
 * @author ThinkGem
 * @version 2013-5-29
 */
public class DictUtils {

    private static DirectoryService directoryService = (DirectoryService) SpringHelper.getBean("directoryService");

    public static final String CACHE_DICT_MAP = "dictMap";

    public static String getDictLabel(String value, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)) {
            List<TDirectory> directories = directoryService.findDirectories(DirectoryType.valueOf(type));
            for (TDirectory dict : directories) {
                if (type.equals(dict.getDirGroup()) && value.equals(dict.getDirValue())) {
                    return dict.getDirCode();
                }
            }
        }
        return defaultValue;
    }

    public static String getDictLabels(String values, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)) {
            List<String> valueList = new ArrayList<String>();
            for (String value : StringUtils.split(values, ",")) {
                valueList.add(getDictLabel(value, type, defaultValue));
            }
            return StringUtils.join(valueList, ",");
        }
        return defaultValue;
    }


    public static String getDictValue(String label, String type, String defaultLabel) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)) {
            List<TDirectory> directories = directoryService.findDirectories(DirectoryType.valueOf(type));
            for (TDirectory dict : directories) {
                if (type.equals(dict.getDirGroup()) && label.equals(dict.getDirCode())) {
                    return dict.getDirValue();
                }
            }
        }
        return defaultLabel;
    }
}
